import React, { memo, ReactNode } from 'react'
import { TopLisItemtWrapper } from './style'
import { getImageSize } from '@/utils/format'
import { useAppDispatch } from '@/store'
import {
  addSongToListAction,
  changePlayingSongAction
} from '@/views/player/store/player'
import { Link } from 'react-router-dom'

interface IProps {
  children?: ReactNode
  itemData: any
}

const TopListItem: React.FC<IProps> = (props) => {
  const { itemData } = props
  const { tracks = [] } = itemData
  const dispatch = useAppDispatch()
  function handleChangeCurrentSong(id: number) {
    dispatch(changePlayingSongAction(id))
  }
  function handleChangeSongList(id: number) {
    dispatch(addSongToListAction(id))
  }
  function playTopList() {
    const needTrackIds = tracks
      ?.slice(0, 10)
      .map((track: any) => track.id)
      .join(',')
    dispatch(changePlayingSongAction(needTrackIds))
  }
  return (
    <TopLisItemtWrapper>
      <div className="header">
        <div className="image">
          <img
            src={getImageSize(itemData.playlist.coverImgUrl, 80, 80)}
            alt={itemData.playlist.description}
          />
          <Link className="cover sprite_cover" to="/discover/ranking"></Link>
        </div>
        <div className="info">
          <a className="name" href="#/discover/ranking">
            {itemData.playlist.name}
          </a>
          <div>
            <button
              className="btn sprite_02 play"
              onClick={() => playTopList()}
              title="播放"
            ></button>
            <button className="btn sprite_02 favor" title="收藏"></button>
          </div>
        </div>
      </div>
      <div className="list">
        {tracks.map((item: any, index: number) => {
          return (
            <div className="list-item" key={item.id}>
              <div className="rank">{index + 1}</div>
              <div className="name">{item.name}</div>
              <div className="operator">
                <button
                  className="btn sprite_02 play"
                  onClick={() => handleChangeCurrentSong(item.id)}
                ></button>
                <button
                  className="btn sprite_icon2 add"
                  onClick={() => handleChangeSongList(item.id)}
                ></button>
                <button className="btn sprite_02 favor"></button>
              </div>
            </div>
          )
        })}
      </div>
      <div className="footer">
        <a href="#/discover/ranking">查看全部&gt;</a>
      </div>
    </TopLisItemtWrapper>
  )
}

export default memo(TopListItem)
